import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'; // 引入 useRouter
import * as userApi from '../api/users.api.js';
import { ResponseStatus } from '../utils/enums.js'
export const useUserStore = defineStore('counter', () => {
    // 定义一个响应式变量 username
    const username = ref('啊啊啊')
    // 定义一个响应式变量 登录状态
    const isLogin = ref(true)
    // 定一个令牌字符串 token
    const token = ref('aaa')
    const router = useRouter(); // 获取路由实例

    async function login(userName: string, password: string, path = '/') {
        // 登录
        let res: ResponseObject<User> = await userApi.login(userName, password)
        if (res.status !== ResponseStatus.success) {
            throw res.message
        }
        username.value = res.data.userName
        token.value = res.data.token
        isLogin.value = true
        if (!!path) {
            // 导航到默认首页
            router.push(path);
        }
        return res
    }

    async function logout(path='/login') {
        // 退出登录
        let res: ResponseObject<any> = await userApi.logout()
        if (res.status !== ResponseStatus.success) {
            throw res.message
        }
        username.value = ''
        token.value = ''
        isLogin.value = false
        // 导航到登录页
        if (!!path) {
            // 导航到默认首页
            router.push(path);
        }
    }

    return { username, isLogin, token, login, logout }
})
